<?php
/**
 * VIP等级
 */

namespace App\backend\controllers\member;

use App\backend\models\MemberLevelModel;
use App\backend\services\MemberLevelServices;
use App\backend\controllers\AdminBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MemberLevelController extends AdminBaseController
{

    /**
     * 列表
     */
    public function list(Request $request)
    {
        $groupList = MemberLevelModel::getLevelPageList($request);
        $groupList = is_null($groupList) ? [] : $groupList;
        foreach ($groupList['data'] as $k => $v) {
            $groupList['data'][$k]['member_count'] = count($v['member']);
            unset($groupList['data'][$k]['member']);
        }
        return successJson('ok', $groupList);

    }

    /**
     * 添加/编辑
     */
    public function modify(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'level_name' => 'required|string|max:45',
            ],
            [
                'level_name.required' => '等级名称不能为空',
                'level_name.max' => '等级名称长度超过最大限制'
            ]);

        if ($validator->fails()){
            return errorJson($validator->errors()->first());
        }

        $result = MemberLevelServices::levelModify($data);
        if ($result) {
            return successJson('操作成功');
        }
        return errorJson('操作失败');
    }

    /**
     * 删除
     */
    public function delete(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'level_id' => 'required',
            ],
            [
                'level_id.required' => '等级ID不能为空'
            ]);

        if ($validator->fails()){
            return errorJson($validator->errors()->first());
        }

        $result = MemberLevelServices::levelDelete($data);
        if ($result) {
            return successJson('操作成功');
        }
        return errorJson('操作失败');

    }

}
